<?php

namespace model;

use common\Model;

class video_cate extends Model
{
	private static $DB_TABLE = "video_cate";
	protected $DB;

	function __construct()
	{
		$this->DB = parent::db();
	}
	
	public function FindData()
	{
		$where['id'] = $_GET['id'];
		return $this->DB->table(static::$DB_TABLE)->where($where)->find();
	}

	//获取栏目列表
	public function SelectData()
	{
		return $this->DB->table(static::$DB_TABLE)->order('sort DESC')->select();
	}

	//添加数据
	public function insertData()
	{
		if (empty($_POST['name']))
			return ['status' => 0, 'msg' => '请填写必要数据'];
		$data = [
			'name' => VarFilter($_POST['name']),
			'theme' => VarFilter($_POST['theme']) ?? null,
			'sort' => $_POST['sort'] ?: 1,
			'num' => $_POST['num'] ?: 25,
			'ico' => $_POST['ico'],
		];
		$re_key = $this->DB->table(static::$DB_TABLE)->insert($data);
		if ($re_key) {
			SqlLog("添加视频栏目 ID：" . $re_key);
			CleanDbCache(static::$DB_TABLE);
			return ['status' => 1, 'msg' => '添加成功'];
		} else {
			return ['status' => 0, 'msg' => '数据错误！添加失败'];
		}
	}

	//更新数据
	public function updateData()
	{
		if (empty($_POST['name']))
			return ['status' => 0, 'msg' => '请填写必要数据'];

		$where['id'] = $_POST['id'];
		$data = [
			'name' => VarFilter($_POST['name']),
			'theme' => VarFilter($_POST['theme']) ?? null,
			'sort' => $_POST['sort'] ?: 1,
			'num' => $_POST['num'] ?: 25,
			'ico' => $_POST['ico'],
		];
		if ($this->DB->table(static::$DB_TABLE)->Where($where)->Update($data)) {
			SqlLog("修改视频栏目 ID:" . $_POST['id']);
			CleanDbCache(static::$DB_TABLE);

			return ['status' => 1, 'msg' => '修改成功'];
		} else {
			return ['status' => 0, 'msg' => '数据没有变化'];
		}
	}

	//更新排序数据
	public function updateSort()
	{
		$where['id'] = $_GET['id'];
		$data = [
			'sort' => $_POST['sort'],
		];
		if ($this->DB->table(static::$DB_TABLE)->Where($where)->Update($data)) {
			SqlLog("修改视频栏目排序 ID:" . $_GET['id']);
			CleanDbCache(static::$DB_TABLE);
			return  ['status' => 1, 'msg' => '修改成功'];
		} else {
			return  ['status' => 0, 'msg' => '未修改'];
		}
	}

	//删除一条数据
	public function deleteOneData()
	{
		$where['cid'] = $_POST['id'];
		if ($this->DB->table('video')->where($where)->find()) {
			return false; //如该栏目下有内容，拒绝删除
		} else {
			$whereCate['id'] = $_POST['id'];
			SqlLog("删除视频栏目：" . $_POST['id']); //写入日志
			return $this->DB->table(static::$DB_TABLE)->where($whereCate)->Delete();
		}
	}
}
